import { h, onMounted, reactive, ref, toRaw } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "../utils/types";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import {
  getMaterialListApi,
  createMaterialApi,
  updateMaterialApi,
  delMaterialApi,
  getMaterialShowApi,
  updateStatusMaterialApi,
  selectMaterialCategoryApi
} from "@/api/materialApi";
export function useWarehouse() {
  const form = reactive({
    page: 1,
    perPage: 10,
    name: null,
	code: "",
	materialCategoryId: null,
	materialCategorySelect: null
  });
  const formRef = ref();
  const dataList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const indexMethod = (index: number) => {
    return index + 1;
  };
  const getStatusType = (type, text = false) => {
    switch (type) {
      case 1:
        return text ? "启用" : "primary";
      case 2:
        return text ? "禁用" : "danger";
    }
  };
  const switchLoadMap = ref({});
  const columns: TableColumnList = [
    {
      label: "ID",
      prop: "materialId",
      width: 80
    },
    {
      label: "物料名称",
      prop: "name",
	  minWidth: 150
    },
    {
      label: "物料编码",
      prop: "code",
	  minWidth: 170
    },
	{
	  label: "单位",
	  prop: "unit.name",
	  minWidth: 90
	},
	{
	  label: "所属分类",
	  prop: "category.name",
	  minWidth: 100
	},
	{
	  label: "入库策略",
	  prop: "stockInTactic",
	  formatter: (row) => {
	  	return row.stockInTactic === 1?'线路最近': '线路最远'
	  },
	  minWidth: 100
	},
	{
	  label: "出库策略",
	  prop: "stockOutTactic",
	  formatter: (row) => {
	  	return row.stockOutTactic === 1?'先进先出': '临期先出'
	  },
	  minWidth: 100
	},
	
    {
      label: "状态",
      prop: "status",
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.status}
          active-value={1}
          inactive-value={2}
          active-text="启用"
          inactive-text="禁用"
          inline-prompt
          onChange={() => switchChange(scope as any)}
        />
      )
    },
	{
	  label: "所能存放地址",
	  prop: "warehouse",
	  slot: "warehouse",
	  minWidth: 200
	},
	{
	  label: "规格",
	  prop: "spec",
	  minWidth: 120
	},
    {
    	label: "创建者",
    	prop: "createUser.username",
		minWidth: 100
    },
    {
    	label: "创建时间",
    	prop: "createdAt",
		minWidth: 160
    },
    {
    	label: "更新者",
    	prop: "updateUser.username",
		minWidth: 100
    },
    {
    	label: "更新时间",
    	prop: "updatedAt",
		minWidth: 160
    },
	{
		label: "备注",
		prop: "remarks",
		minWidth: 120
	},
    {
      label: "操作",
      fixed: "right",
      slot: "operation",
	  width: 220
    }
  ];
  function switchChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.status === 2 ? "禁用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.name
      }</strong>吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        setTimeout(() => {
          switchLoadMap.value[index] = Object.assign(
            {},
            switchLoadMap.value[index],
            {
              loading: false
            }
          );
          updateStatusMaterialApi({
            materialId: row.materialId,
            status: row.status
          }).then((res) => {
  			if(res?.code === 200) {
  				message("操作成功!", {
  				  type: "success"
  				});
  				onSearch()
  			}
            
          });
        }, 300);
      })
      .catch(() => {
        row.status === 1 ? (row.status = 2) : (row.status = 1);
      });
  }
  function handleSizeChange(val: number) {
    loading.value = true;
    form.page = 1;
    form.perPage = val;
    getMaterialListApi(toRaw(form)).then(res => {
      dataList.value = res.result.list;
      pagination.total = res.result.total;
      pagination.pageSize = res.result.perPage*1;
      pagination.currentPage = 1;
    });

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  function handleCurrentChange(val: number) {
    loading.value = true;
    form.page = val;
    getMaterialListApi(toRaw(form)).then(res => {
      dataList.value = res.result.list;
      pagination.total = res.result.total;
	  pagination.pageSize = res.result.perPage*1;
	  pagination.currentPage = val;
    });

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  async function onSearch() {
    loading.value = true;
    const { result } = await getMaterialListApi(toRaw(form));
    dataList.value = result.list;
    pagination.total = result.total;
    pagination.pageSize = result.perPage*1;
    pagination.currentPage = result.page*1;

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    form.name = null;
    form.code = null;
    form.materialCategoryId = null;
    formEl.resetFields();
    onSearch();
  };
  const formInline = ref();
  async function openDialog(title = "新增", row?: FormItemProps) {
    if (`${title}` == "新增") {
      formInline.value = {
        title: "新增",
        status: 1,
		stockWarn: 2
      };
    } else {
      const res = await getMaterialShowApi({
        materialId: row?.materialId
      });
	  if(res.code !== 200) {
	  	message(res.msg ?? "操作失败,请联系管理员", {
	  	  type: "error"
	  	});
	  	return
	  }
      formInline.value = {
        title: "修改",
        materialId: row?.materialId ?? "",
        name: res?.result?.name ?? "",
        code: res?.result?.code ?? null,
        status: res?.result?.status ?? 1,
		materialUnitId: res?.result?.materialUnitId ?? "",
		materialCategoryId: res?.result?.materialCategoryId ?? "",
		stockInTactic: res?.result?.stockInTactic ?? "",
		stockOutTactic: res?.result?.stockOutTactic ?? "",
		warehouseId: res?.result?.warehouseId ?? "",
		warehouseAreaId: res?.result?.warehouseAreaId ?? "",
		warehouseLocationId: res?.result?.warehouseLocationId ?? "",
		expireType: res?.result?.expireType ?? "",
		expireDate: res?.result?.expireDate ?? "",
		produceDate: res?.result?.produceDate ?? "",
		expireDateNum: res?.result?.expireDateNum ?? "",
		stockWarn: res?.result?.stockWarn ?? "",
		stockWarnMin: res?.result?.stockWarnMin ?? "",
		stockWarnMax: res?.result?.stockWarnMax ?? "",
		spec: res?.result?.spec ?? "",
		remarks: res?.result?.remarks ?? "",
		length: res?.result?.length ?? "",
		width: res?.result?.width ?? "",
		height: res?.result?.height ?? "",
		volume: res?.result?.volume ?? "",
		weight: res?.result?.weight ?? "",
		warehouseArr: [res?.result?.warehouseId ?? ""]
      };
	  if(res?.result?.warehouseAreaId) {
		formInline.value.warehouseArr.push(res?.result?.warehouseAreaId)
	  }
	  if(res?.result?.warehouseLocationId) {
	  	formInline.value.warehouseArr.push(res?.result?.warehouseLocationId)
	  }
    }
	formInline.value.materialCategorySelect = materialCategorySelect.value
    addDialog({
      title: `${title}物料`,
      props: {
        formInline: formInline
      },
      width: "820px",
	  top: "10vh",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了物料`, {
            type: "success"
          });
          done();
          onSearch();
        }
		curData.length = curData.length && curData.length > 0 ? Number(curData.length).toFixed(2):null
		curData.width = curData.width && curData.width > 0 ? Number(curData.width).toFixed(2):null
		curData.height = curData.height && curData.height > 0 ? Number(curData.height).toFixed(2):null
		curData.volume = curData.volume && curData.volume > 0 ? Number(curData.volume).toFixed(2):null
		curData.weight = curData.weight && curData.weight > 0 ? Number(curData.weight).toFixed(2):null
        FormRef.validate(valid => {
          if (valid) {
            if (title === "新增") {
              createMaterialApi(nullObj(curData))
                .then((res) => {
				  if(res.code !== 200) {
				  	message(res.msg ?? "操作失败,请联系管理员", {
				  	  type: "error"
				  	});
				  	return
				  }
                  chores();
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
            } else {
              updateMaterialApi(nullObj(curData))
                .then((res) => {
				  if(res.code !== 200) {
				  	message(res.msg ?? "操作失败,请联系管理员", {
				  	  type: "error"
				  	});
				  	return
				  }
                  chores();
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
            }
          }
        });
      }
    });
  }
  function nullObj(obj) {
  	   for (const key in obj) {
  		  if (obj[key] === 0 || obj[key] === "" || obj[key] === null) {
  			  delete obj[key];
  		  }
  	  }
  	  return obj
  }
  const materialCategorySelect = ref([])
  async function getSelectMaterialCategory() {
	  const res = await selectMaterialCategoryApi()
	  if(res?.code ===200) {
		  materialCategorySelect.value = res.result
		  form.materialCategorySelect = materialCategorySelect.value
	  }
  }
  onMounted(async () => {
    onSearch();
	getSelectMaterialCategory()
  });

  function handleDelete(row) {
    delMaterialApi({ materialId: row.materialId }).then((res) => {
	  if(res.code !== 200) {
	  	message(res.msg ?? "操作失败,请联系管理员", {
	  	  type: "error"
	  	});
	  	return
	  }
      message(`删除成功`, { type: "success" });
      onSearch();
    });
  }
  return {
    form,
    isShow,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleSizeChange,
    handleCurrentChange,
    deviceDetection,
    handleDelete
  };
}
